package com.kwin.rpcserver.scan;

import com.kwin.rpccommon.annotation.RpcController;
import com.kwin.rpcserver.holder.RpcBeanHolder;
import com.kwin.rpcserver.netty.worker.RpcServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author : wangkai
 * @version V1.0
 * @Package com.kwin.rpcserver.scan
 * @Description:
 * @date 2021年07月30日 15:56
 **/
@Slf4j
public class RpcServerApplicationContextAware implements ApplicationContextAware, InitializingBean {

//    ServerWorker runner;
    RpcServer rpcServer;
    
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        String port = applicationContext.getEnvironment().getProperty("rpc.port");
        port = StringUtils.hasText(port) ? port : "8010";
        String idleTime = applicationContext.getEnvironment().getProperty("rpc.idleTime");
        idleTime = StringUtils.hasText(idleTime) ? idleTime : "60";
        
        Map<String, Object> beans = applicationContext.getBeansWithAnnotation(RpcController.class);
        for (Object serviceBean : beans.values()) {
            
            Class<?> clazz = serviceBean.getClass();
            
            Class<?>[] interfaces = clazz.getInterfaces();
            
            for (Class<?> inter : interfaces) {
                String interfaceName = inter.getName();
                RpcBeanHolder.put(interfaceName, serviceBean);
            }
        }
        // 创建netty worker对象
        rpcServer = new RpcServer(Integer.parseInt(port), Integer.parseInt(idleTime));
//        runner = new ServerWorker(address, serviceMap);
    }
    
    @Override
    public void afterPropertiesSet() throws Exception { // 创建netty socketServer及通道处理器
        rpcServer.start();
    }
}